package com.huahua.api.controller.utility;

import com.huahua.api.entity.base.R;
import com.huahua.api.entity.param.TableComparisonParam;
import com.huahua.api.entity.vo.tablecomparison.TableComparisonVO;
import com.huahua.api.exception.CommonException;
import com.huahua.api.service.TableComparisonService;
import com.huahua.api.util.CheckUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/api/utility/table-comparison")
@RequiredArgsConstructor
@Slf4j
public class TableComparisonController {

    private final TableComparisonService tableComparisonService;

    @PostMapping("/compare")
    public Mono<R<TableComparisonVO>> compare(@RequestBody TableComparisonParam param) {
        return Mono.fromCallable(() -> {
                    CheckUtil.checkStrNotBlank(param.getTable1Url(), new CommonException("表格1地址不能为空"));
                    CheckUtil.checkStrNotBlank(param.getTable2Url(), new CommonException("表格2地址不能为空"));
                    return param;
                })
                .flatMap(tableComparisonService::compare)
                .map(R::success)
                .onErrorResume(e -> {
                    log.error("表格对比失败", e);
                    return Mono.just(R.error(e.getMessage()));
                });
    }

    @GetMapping("/download/{comparisonId}")
    public Mono<ResponseEntity<Flux<DataBuffer>>> download(@PathVariable String comparisonId) {
        CheckUtil.checkStrNotBlank(comparisonId, new CommonException("对比任务ID不能为空"));

        return tableComparisonService.downloadResult(comparisonId)
                .map(dataBufferFlux -> ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION,
                                "attachment; filename=table_comparison_result_" + System.currentTimeMillis() + ".csv")
                        .contentType(MediaType.TEXT_PLAIN)
                        .body(dataBufferFlux))
                .defaultIfEmpty(ResponseEntity.notFound().build());
    }
}
